package com.scalar.chiptrack.operations.process.actions;

import com.scalar.chiptrack.ChipTrackAction;
import com.scalar.chiptrack.db.DBTransaction;
import com.scalar.chiptrack.commons.SessionKeys;
import com.scalar.chiptrack.users.User;
import com.scalar.chiptrack.users.Functionality;
import com.scalar.chiptrack.operations.process.forms.GroupFabStageForm;
import com.scalar.chiptrack.operations.process.dao.GroupAssemblyStagesDAO;
import com.scalar.chiptrack.operations.process.dao.FabStage;
import com.scalar.chiptrack.operations.process.dao.FinishedGoodsDAO;
import com.scalar.chiptrack.operations.process.FabStageGroup;

import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionForm;
import org.apache.struts.util.LabelValueBean;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.HashMap;

/**
 *  Process the requests comming from Group Assembly Stage Screen
 *
 * Created by Veeru.
 * Date: May 17, 2005
 * Time: 4:17:55 PM
 */

public class GroupAssemblyStagesAction extends ChipTrackAction {

    public static final String ACTION_NAME = "/groupAssemblyStage.do";

    public ActionForward execute( ActionMapping mapping,
                                  ActionForm form,
                                  HttpServletRequest request,
                                  HttpServletResponse response ) throws Exception {

        GroupFabStageForm groupFabStageForm = ( GroupFabStageForm ) form;
        FabStage fabStage = groupFabStageForm.getFabStage();
        HttpSession session = request.getSession();
        User user = ( User ) session.getAttribute( SessionKeys.USER_KEY );

        if ( user == null )
        {
            session.setAttribute( SessionKeys.SOURCE_PAGE_KEY, ACTION_NAME + "?"+ request.getQueryString() );
            return mapping.findForward("login");
        }
        ArrayList groupsList = new ArrayList();
        String action = request.getParameter("action");
        HashMap info   = new HashMap();
        HashMap errors = new HashMap();
        request.setAttribute( SessionKeys.INFO_MESSAGES, info );
        request.setAttribute( SessionKeys.ERROR_MESSAGES, errors );

        int processStepId = fabStage.getProcessStepId();
        int locationId    = fabStage.getLocationId();
        FabStageGroup fabStageGroup = null;
        ArrayList selectedStagesList = new ArrayList();

        request.setAttribute ( "vendorsList", GroupAssemblyStagesDAO.loadAssemblyVendorLocations( null ) );

        if ( action == null )
        {
            fabStage = new FabStage();
        }
        if ( "loadPartNumbers".equalsIgnoreCase( action ) )
        {
            if ( fabStage.getLocationId() > 0 )
            {
                fabStage.setProcessStepId( 0 );
                request.setAttribute( "partNumbersList", GroupAssemblyStagesDAO.loadAssemblyPartNumbers( null, fabStage.getLocationId() ) );
                request.setAttribute( "displayPartNumbers", "true" );
            }
        }
        if ( "loadGroups".equalsIgnoreCase( action ) )
        {
            if ( fabStage.getProcessStepId() > 0 )
            {
                fabStage.setTotalGroupNo( 0 );
                for ( int i = 1; i < 99; i++ )
                {
                    groupsList.add( new LabelValueBean( i+"", i+"" ) );
                }
                ArrayList stageGroupsList = GroupAssemblyStagesDAO.loadAssemblyStageGroups( null, processStepId ,  locationId );
                ArrayList availableStagesList = GroupAssemblyStagesDAO.loadAssemblyStages( null, processStepId, locationId );

                int defaultGroupProcessStepId =  GroupAssemblyStagesDAO.getDefaultGroupProcessStepId( null, locationId );

                if ( defaultGroupProcessStepId == processStepId )
                {
                    fabStage.setIsDefault( true );
                    session.setAttribute( "disableIsDefault", "false" );
                }
                else if ( defaultGroupProcessStepId > 0 )
                {
                    fabStage.setIsDefault( false );
                    info.put( "Default Group exists for the part number "+ FinishedGoodsDAO.getPartNumber( null, defaultGroupProcessStepId ), null );
                    session.setAttribute( "disableIsDefault", "true" );
                }
                else
                {
                    session.setAttribute( "disableIsDefault", "false" );
                }
                if ( stageGroupsList.size() > 0 )
                {

                    fabStage.setTotalGroupNo( stageGroupsList.size() );
                    for ( int i = 0; i < stageGroupsList.size(); i++ )
                    {
                        fabStageGroup = ( FabStageGroup ) stageGroupsList.get ( i );
                        selectedStagesList = GroupAssemblyStagesDAO.loadSelectedStages( null, fabStageGroup.getGroupId() );
                        fabStageGroup.setSelectedStagesList( selectedStagesList );
                    }
                    fabStageGroup = ( FabStageGroup ) stageGroupsList.get ( 0 );
                    fabStageGroup.setAvailableStagesList( availableStagesList );

                    request.setAttribute( "showStages", "true" );
                    if ( user.isActionAllowed ( Functionality.GROUP_ASSEMBLY_STAGES, User.USER_ACTION_DELETE ) == true )
                    {
                        request.setAttribute( "showRemove" , "true" );
                    }
                    session.setAttribute( "disable", "true" );
                }
                else
                {
                    request.setAttribute( "showStages", "false" );
                    request.setAttribute( "showRemove" , "false");
                    session.setAttribute( "disable", "false" );
                }
                fabStage.setFabStages( stageGroupsList );
                request.setAttribute( "availableStageList", availableStagesList );
                session.setAttribute( "groupsList", groupsList );
                request.setAttribute( "showGroupNumbers", "true" );
            }
            request.setAttribute( "partNumbersList", GroupAssemblyStagesDAO.loadAssemblyPartNumbers( null, locationId ) );
            request.setAttribute( "displayPartNumbers", "true" );
        }
        if ( "loadStages".equalsIgnoreCase( action ) )
        {
            if ( fabStage.getTotalGroupNo() > 0 )
            {
                ArrayList stagesList = new ArrayList();
                for (int i = 0; i < fabStage.getTotalGroupNo(); i++)
                {
                    stagesList.add( new FabStageGroup() );
                }
                fabStage.setFabStages( stagesList );
                request.setAttribute( "availableStageList", GroupAssemblyStagesDAO.loadAssemblyStages( null, fabStage.getProcessStepId(), fabStage.getLocationId() ) );
                request.setAttribute( "showStages", "true" );
            }
            request.setAttribute( "partNumbersList", GroupAssemblyStagesDAO.loadAssemblyPartNumbers( null, fabStage.getLocationId() ) );
            request.setAttribute( "displayPartNumbers", "true" );
            request.setAttribute( "showGroupNumbers", "true" );
        }
        if ( "addAssemblyStage".equalsIgnoreCase( action ) )
        {
            return mapping.findForward( "addAssemblyStage" );
        }
        if ( "saveAssemblyStage".equalsIgnoreCase( action ) )
        {
            DBTransaction dbTransaction = null;
            boolean success = false;
            try
            {
                if ( GroupAssemblyStagesDAO.isAssemblyStageExists( null, fabStage.getProcessStepId() , groupFabStageForm.getFabstageName() ) )
                {
                    errors.put( groupFabStageForm.getFabstageName() + "  Already Exists in the Database", null );
                    groupFabStageForm.reset( mapping,request );
                    request.setAttribute("showList" , "true");
                    return mapping.findForward( "saveAssemblyStage" );
                }
                dbTransaction = DBTransaction.getInstance ();
                dbTransaction.begin ();
                GroupAssemblyStagesDAO.saveAssemblyStage( dbTransaction, fabStage.getProcessStepId(), groupFabStageForm.getFabstageName() );
                success = true;
            }
            catch(Exception e1)
            {
                e1.printStackTrace();
            }
            finally
            {
                if( dbTransaction != null )
                {
                    if( success == true )
                    {
                        groupFabStageForm.reset( mapping,request );
                        info.put( "Assembly Stage Name Saved Successfully",null );
                        dbTransaction.commit();
                    }
                    else
                    {
                        errors.put( "Could not save the Assembly Stage information ", null );
                        dbTransaction.rollback();
                    }
                }
            }
            return mapping.findForward( "saveAssemblyStage" );
        }
        if ( "reloadStages".equalsIgnoreCase( action ) )
        {
            ArrayList fabStages = fabStage.getFabStages();
            FabStageGroup stageGroup = null;
            String selectedStages[]  = null;
            String availableStages[] = null;
            ArrayList availableStageList = new ArrayList();
            ArrayList tempList = new ArrayList();
            try
            {
                for ( int i = 0; i < fabStages.size(); i++ )
                {
                    stageGroup = ( FabStageGroup )fabStages.get( i );
                    selectedStages = stageGroup.getSelectedStages();
                    if ( selectedStages != null && selectedStages.length > 0 )
                    {
                        selectedStagesList = GroupAssemblyStagesDAO.convertPartsArrayToList(  selectedStages );
                        stageGroup.setSelectedStagesList( selectedStagesList );
                        for (int j = 0; j < selectedStagesList.size(); j++) {
                            LabelValueBean bean = (LabelValueBean) selectedStagesList.get(j);
                            tempList.add( bean.getLabel() );
                        }
                    }
                }
                stageGroup = ( FabStageGroup )fabStages.get( 0 );
                availableStages = stageGroup.getAvailableStages();
                if ( availableStages != null && availableStages.length > 0 )
                {
                    availableStageList = GroupAssemblyStagesDAO.convertPartsArrayToList( availableStages );
                }
                for (int i = 0; i < availableStageList.size(); i++) {
                    LabelValueBean bean = (LabelValueBean) availableStageList.get(i);
                    tempList.add( bean.getLabel() );
                }
                ArrayList availableStageListFromDB =  GroupAssemblyStagesDAO.loadAssemblyStages( null, fabStage.getProcessStepId(), fabStage.getLocationId() );
                for (int i = 0; i < availableStageListFromDB.size(); i++) {
                    LabelValueBean bean = (LabelValueBean) availableStageListFromDB.get(i);
                    if ( tempList.contains( bean.getLabel() ) == false )
                    {
                        availableStageList.add( bean );
                    }
                }
            }
            catch( Exception e )
            {
                e.printStackTrace();
            }
            request.setAttribute( "partNumbersList", GroupAssemblyStagesDAO.loadAssemblyPartNumbers( null, fabStage.getLocationId() ) );
            request.setAttribute( "availableStageList", availableStageList );
            request.setAttribute( "displayPartNumbers", "true" );
            request.setAttribute( "showGroupNumbers", "true" );
            request.setAttribute( "showStages", "true" );
            request.setAttribute( "showRemove" , "true");
        }
        if ( "addMore".equalsIgnoreCase( action ) )
        {
            ArrayList fabStages = fabStage.getFabStages();
            FabStageGroup stageGroup = null;
            String selectedStages[]  = null;
            String availableStages[] = null;
            ArrayList availableStageList = new ArrayList();
            try
            {
                for ( int i = 0; i < fabStages.size(); i++ )
                {
                    stageGroup = ( FabStageGroup )fabStages.get( i );
                    selectedStages = stageGroup.getSelectedStages();
                    if ( selectedStages != null && selectedStages.length > 0 )
                    {
                        stageGroup.setSelectedStagesList( GroupAssemblyStagesDAO.convertPartsArrayToList(  selectedStages ) );
                    }
                }
                stageGroup = ( FabStageGroup )fabStages.get( 0 );
                availableStages = stageGroup.getAvailableStages();
                if ( availableStages != null && availableStages.length > 0 )
                {
                    availableStageList = GroupAssemblyStagesDAO.convertPartsArrayToList( availableStages );
                }
                stageGroup =  new FabStageGroup();
                stageGroup.setIsNewGroup( true );
                stageGroup.setAvailableStagesList( availableStageList );
                fabStages.add( stageGroup );
                fabStage.setTotalGroupNo( fabStage.getTotalGroupNo() + 1 );
            }
            catch( Exception e )
            {
                e.printStackTrace();
            }
            request.setAttribute( "partNumbersList", GroupAssemblyStagesDAO.loadAssemblyPartNumbers( null, fabStage.getLocationId() ) );
            request.setAttribute( "availableStageList", availableStageList );
            request.setAttribute( "displayPartNumbers", "true" );
            request.setAttribute( "showGroupNumbers", "true" );
            request.setAttribute( "showStages", "true" );
            request.setAttribute( "showRemove" , "true");
        }
        if ( "saveStageGroups".equalsIgnoreCase( action ) )
        {
            DBTransaction dbTransaction = null;
            boolean success = false;
            try
            {
                dbTransaction = DBTransaction.getInstance ();
                dbTransaction.begin ();

                GroupAssemblyStagesDAO.saveStageGroups( dbTransaction, fabStage );

                fabStage.setLocationId( 0 );
                fabStage.setProcessStepId( 0 );
                groupFabStageForm.setFabStage( fabStage );
                success = true;
            }
            catch (Exception e) {
                fabStage.setLocationId( 0 );
                fabStage.setProcessStepId( 0 );
                e.printStackTrace();
            }
            finally
            {
                try
                {
                    if( dbTransaction != null )
                    {
                        if( success == true )
                        {
                            dbTransaction.commit();
                            info.put ("Assembly Stage Groups have been saved successfully", null);
                        }
                        else
                        {
                            dbTransaction.rollback();
                            errors.put ("Unable to save Assembly Stage Groups into Data Base", null);
                        }
                    }
                }
                catch(Exception e1)
                {
                    e1.printStackTrace();
                }
            }
        }
        groupFabStageForm.setFabStage( fabStage );
        return mapping.findForward("success");
    }
}
